import java.util.Arrays;

public class MyHeap {
    int[] elem;
    int useSized;

    public MyHeap() {
        elem = new int[10];
    }

    public void init(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            this.elem[i] = arr[i];
        }
        useSized = arr.length;
    }

    public void creatHeap() {
        for (int parent = (useSized - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(elem,parent,this.useSized);
        }
    }

    private void swap(int[] elem,int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public void shiftDown(int[] elem,int parent,int useSized) {
        int child = 2 * parent + 1;  // 获取左孩子
        while(child < useSized) {
            if(child+1 < useSized && elem[child+1] < elem[child]) {  //先判断有没有右孩子，再判断左右孩子谁小
                child++;
            }
            if(elem[parent] > elem[child]) {
                //交换
                swap(elem,parent,child);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break; // 说明本身就是小根堆，直接退出循环
            }
        }
    }

    public void offer(int val) {
        if(isFull()) {
            grow();
        }
        elem[useSized] = val;
        //向上调整
        shirtUp(useSized);
        useSized++;
    }

    public void shirtUp(int child) {
        int parent = (child - 1) / 2;
        while(parent >= 0) {
            if(elem[child] < elem[parent]) {
                swap(elem,child,parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    private void grow() {
        elem = Arrays.copyOf(elem,2 * elem.length);
    }

    public boolean isFull() {
        return useSized == elem.length;
    }

    public int poll() {
        if(isEmpty()) {
            return -1;
        }

        int ret = elem[0];
        swap(elem,0,useSized-1);
        useSized--;
        shiftDown(elem,0,useSized);
        return ret;
    }

    public boolean isEmpty() {
        return useSized == 0;
    }

    public int peek() {
        if(isEmpty()) {
            return -1;
        }
        return elem[0];
    }
}
